<!--  -->
<template>
    <page-header-wrapper @back="() => $router.go(-1)" class="detail">
        <template v-slot:content>
            <div class="page-header-content">
                <div class="flex spaceBetween alignCenter" style="width: 100%">
                    <div class="flex alignCenter">
                        <div>账户余额：<span style="color: red">￥{{balance}}</span></div>
                        <a-switch v-if="account.linkageType == 1 && hasPayPassword" :disabled="isCheck" style="margin-left: 200px" checked-children="需要交易密码" un-checked-children="不需要交易密码" :checked="account.needDealPassword == '0' ? false : true" @change="needDealPasswordOnChange" />
                    </div>
                    <div>
                        <a-button type='' style="margin-right: 20px" @click="setAddRemark">设置充值信息</a-button>
                        <a-button v-if="!hasPayPassword && ( account.linkageType == 1)" type='' style="margin-right: 20px" @click="setPayPassword">设置交易密码</a-button>
                        <a-button v-if="hasPayPassword && ( account.linkageType == 1)" type='' style="margin-right: 20px" @click="updatePayPasswordBtn">修改交易密码</a-button>
                        <a-button v-if="hasPower('updateLaborWithdrawalAccount') && (account.linkageType == 1)" type='' @click="setWidthdraw">设置提现账户</a-button>
                    </div>
                </div>
                <br>
                <a-descriptions size="small">
                    <a-descriptions-item label="账户名称" >{{account.accountName}}</a-descriptions-item>
                    <a-descriptions-item label="银行账号" :span="2">{{account.bankAccount}}</a-descriptions-item>
                    <a-descriptions-item label="账户简称" >{{account.accountShortName == '' || !account.accountShortName ? '-' : account.accountShortName}}</a-descriptions-item>
                    <a-descriptions-item label="开户行" :span="2">{{account.channel}}</a-descriptions-item>
                    <a-descriptions-item label="账户类型" >{{account.accountType | accountTypeFilter}}</a-descriptions-item>
                    <a-descriptions-item label="所属公司" :span="2">{{account.companyName ?? '-'}}</a-descriptions-item>
                    <a-descriptions-item label="所属客户" >{{account.customerName ?? '-'}}</a-descriptions-item>
                    <a-descriptions-item label="联动设置" :span="2">{{account.linkageType | linkageTypeFilter}}</a-descriptions-item>
                    <a-descriptions-item :label="`${account.linkageType == 1 ? '授权方' : '发起方'}账户`" v-if="account.linkageType != 0" :span="3">
                        <div class="flex alignCenter" v-for="linkageAccount in account.linkageAccounts" :key="linkageAccount.bankAccount">
                            <div style="margin-right: 10px">{{linkageAccount.accountName}}({{linkageAccount.bankAccount}})</div>
                        </div>
                    </a-descriptions-item>
                    <a-descriptions-item v-if="account.laborSubAccount" label="额度控制" >{{account.laborSubAccount.quotaWay == 'N' ? '不允许透支' : '允许透支'}}</a-descriptions-item>
                    <a-descriptions-item v-if="account.laborSubAccount" label="退票方式" >{{account.laborSubAccount.refundWay == 'N' ? '退回结算户' : '退回原记账子单元'}}</a-descriptions-item>
                </a-descriptions>
            </div>
        </template>

        <a-card :bordered="false">
            <a-tabs default-active-key="1">
                <a-tab-pane key="1" tab="充值记录" force-render>
                    <addBill :accountId="accountId"/>
                </a-tab-pane>
                <a-tab-pane key="2" tab="提现记录" force-render>
                    <withdrawBill :accountId="accountId" />
                </a-tab-pane>
                <a-tab-pane key="3" tab="交易流水记录" force-render>
                    <orderBill :accountId="accountId"/>
                </a-tab-pane>
            </a-tabs>
        </a-card>

        <!-- 设置充值信息 -->
        <a-modal 
            v-model="visible" 
            title="设置充值信息"
            @ok="handleOk" 
            :forceRender="true"
            @cancel="visible = false">
            <div>
                <a-form-model >
                    <a-form-model-item>
                        <a-textarea v-model="rechargeInfo" placeholder="请输入该账户下的充值注意事项，最多1000字" allowClear :maxLength="1000" :auto-size="{ minRows: 5, maxRows: 6 }" />
                    </a-form-model-item>
                </a-form-model>
            </div>
        </a-modal>

        <!-- 提现账户配置 -->
        <a-modal 
            v-model="withdrawConfigVisible" 
            title="设置提现账户信息"
            @ok="withdrawConfigHandleOk" 
            :forceRender="true"
            @cancel="withdrawConfigVisible = false">
            <div>
                <a-form-model :model="withdrawAccount" ref="ruleForm" :rules="rules" :label-col="{ span: 7 }" :wrapper-col="{ span: 17 }">
                    <a-form-model-item label="开户行" prop="withdrawalChannel">
                        <a-input v-model="withdrawAccount.withdrawalChannel" placeholder="请输入开户行信息" />
                    </a-form-model-item>
                    <a-form-model-item label="账户名称" prop="withdrawalAccountName">
                        <a-input v-model="withdrawAccount.withdrawalAccountName" placeholder="请输入账户名称" />
                    </a-form-model-item>
                    <a-form-model-item label="银行账号" prop="withdrawalBankAccount">
                        <a-input v-model="withdrawAccount.withdrawalBankAccount" placeholder="请输入银行账号" />
                    </a-form-model-item>
                    <a-form-model-item label="开户地" >
                        <a-input v-model="withdrawAccount.withdrawalSubChannel" placeholder="请输入开户地信息" />
                    </a-form-model-item>
                </a-form-model>
            </div>
        </a-modal>

        <!-- 设置交易密码 -->
        <a-modal 
            v-model="payPasswordVisible" 
            title="设置交易密码"
            @ok="payPasswordHandleOk" 
            :forceRender="true"
            @cancel="payPasswordVisible = false">
            <div>
                <a-form-model :model="payPassword" ref="payPasswordRuleForm" :rules="payPasswordRules" :label-col="{ span: 7 }" :wrapper-col="{ span: 17 }">
                    <a-form-model-item label="验证码" prop="verifyCode">
                        <a-row :gutter="16">
                            <a-col class="gutter-row" :span="16">
                                <a-input v-model="payPassword.verifyCode" placeholder="请输入验证码" />
                            </a-col>
                            <a-col class="gutter-row" :span="8">
                                <a-button class="getCaptcha" :disabled="smsSendBtn" @click.stop.prevent="getCaptcha" v-text="!smsSendBtn && $t('获取验证码')||(time+' s')"></a-button>
                            </a-col>
                        </a-row>
                    </a-form-model-item>
                    <a-form-model-item label="交易密码" prop="dealPassword">
                        <a-input-password v-model="payPassword.dealPassword" placeholder="请输入交易密码" />
                    </a-form-model-item>
                    <a-form-model-item label="确认密码" prop="confirmPassword">
                        <a-input-password v-model="payPassword.confirmPassword" placeholder="请再次输入交易密码" />
                    </a-form-model-item>
                </a-form-model>
            </div>
        </a-modal>
        <!-- 修改交易密码 -->
        <a-modal 
            v-model="updatePayPasswordVisible" 
            title="修改交易密码"
            @ok="updatePayPasswordHandleOk" 
            :forceRender="true"
            @cancel="updatePayPasswordVisible = false">
            <div>
                <a-form-model :model="updatePayPasswords" ref="updatePayPasswordRuleForm" :rules="updatePayPasswordRules" :label-col="{ span: 7 }" :wrapper-col="{ span: 17 }">
                    <a-form-model-item label="旧密码" prop="oldPassword">
                        <a-row :gutter="16">
                            <a-col class="gutter-row" :span="16">
                                <a-input v-model="updatePayPasswords.oldPassword" placeholder="请输入旧密码" />
                            </a-col>
                            <a-col class="gutter-row" :span="8">
                                <a-button type="link" class="getCaptcha" @click="forgetPassword">忘记密码？</a-button>
                            </a-col>
                        </a-row>
                    </a-form-model-item>
                    <a-form-model-item label="交易密码" prop="dealPassword">
                        <a-input-password v-model="updatePayPasswords.dealPassword" placeholder="请输入交易密码" />
                    </a-form-model-item>
                    <a-form-model-item label="确认密码" prop="confirmPassword">
                        <a-input-password v-model="updatePayPasswords.confirmPassword" placeholder="请再次输入交易密码" />
                    </a-form-model-item>
                </a-form-model>
            </div>
        </a-modal>
    </page-header-wrapper> 
</template>

<script>
import { getLaborAccountDetail , updateWithdrawAccountConfig , getLaborWithdrawConfig , setPayPassword , updatePayPassword , getHasPayPassword , updateAccountRechargeInfo , getAccountRechargeInfo , changeAccountDealPasswordStatus , getAccountBalance } from '@/api/services/account';
import { getSmsCaptcha } from '@/api/login';
import addBill from './components/addBill';
import orderBill from './components/orderBill';
import withdrawBill from './components/withdrawBill';
import storage from 'store'
export default {
    components: {
        addBill,
        orderBill,
        withdrawBill,
    },
    data () {
        return {
            balance: 0, // 账户余额
            account: {
                id: '',
                accountName: '', // 账户名称
                bankAccount: '', // 银行账号
                accountShortName: '', // 账户简称
                channel: '', // 开户行
                accountType: 1, // 账户类型
                customerName: null, // 所属客户
                companyName: null, // 所属公司
                linkageType: 0, // 联动设置
            },
            rechargeInfo: '', // 充值信息
            visible: false,
            withdrawConfigVisible: false,
            withdrawAccount: {
                accountId: '',
                withdrawalAccountName: '', // 账户名称
                withdrawalBankAccount: '', // 银行账户
                withdrawalChannel: '', // 开户行
                withdrawalSubChannel: '', // 开户支行
            },
            rules: {
                withdrawalChannel: [
                    { required: true, message: '请输入开户行信息', trigger: 'blur' },
                ],
                withdrawalBankAccount: [{ required: true, message: '请输入银行账户', trigger: 'blur' }],
                withdrawalAccountName: [{ required: true, message: '请输入账户名称', trigger: 'blur' }],
            },
            payPasswordVisible: false,
            payPassword: {
                accountId: '',
                dealPassword: '', // 交易密码
                confirmPassword: '', // 确认密码
                verifyCode: '', // 验证码
            },
            payPasswordRules: {
                verifyCode: [
                    { required: true, message: '请输入验证码', trigger: 'blur' },
                ],
                dealPassword: [
                    { required: true, message: '请输入交易密码', trigger: 'blur' },
                    { pattern: /^\d{6}$/ , message: '交易密码只能为6位纯数字',trigger: 'blur'}
                ],
                confirmPassword: [{ required: true, message: '请再次输入交易密码', trigger: 'blur' },{ validator: this.handlePasswordCheck }],
            },
            smsSendBtn: false,
            time: 60,
            userPhone: sessionStorage.getItem('userPhone'),
            hasPayPassword: false,
            updatePayPasswordVisible: false,
            updatePayPasswords: {
                accountId: '',
                dealPassword: '', // 交易密码
                confirmPassword: '', // 确认密码
                oldPassword: '', // 旧密码
            },
            updatePayPasswordRules: {
                oldPassword: [
                    { required: true, message: '请输入旧密码', trigger: 'blur' },
                ],
                dealPassword: [
                    { required: true, message: '请输入交易密码', trigger: 'blur' },
                    { pattern: /^\d{6}$/ , message: '交易密码只能为6位纯数字',trigger: 'blur'}
                ],
                confirmPassword: [{ required: true, message: '请再次输入交易密码', trigger: 'blur' },{ validator: this.handlePasswordCheck }],
            },
            accountId: '',
            isCheck: false,
        };
    },
    async created(){
        if(this.$route.query.accountId){
            this.getDetail(this.$route.query.accountId)
            this.accountId = this.$route.query.accountId;
            this.withdrawAccount.accountId = this.$route.query.accountId;
            this.payPassword.accountId = this.$route.query.accountId;
            this.updatePayPasswords.accountId = this.$route.query.accountId;
            console.log(this.$store.state.user.info,'store')
            this.getHasPaypassword();
            try {
                this.balance = await this.getAccountBalances(this.accountId);
            } catch (error) {
                this.$notification['error']({
                    message: '温馨提示',
                    description: error,
                    duration: 8
                })
            }
        }
    },
    methods: {
        getDetail(accountId){
            let _this = this
            getLaborAccountDetail(accountId)
            .then(res=>{
                if(res.success){
                    _this.account = JSON.parse(JSON.stringify(res.data));
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 获取账户余额信息
        getAccountBalances(id){
            let _this = this;
            return new Promise((resolve,reject) => {
                getAccountBalance(id)
                .then( res => {
                    if(res.success){
                        resolve(res.data)
                    }else{
                        reject(res.errMessage)
                    }
                })
                .catch(err => {
                    reject(err)
                })
            })
        },
        // 设置充值信息
        setAddRemark(){
            let _this = this;
            getAccountRechargeInfo(_this.account.id)
            .then(res => {
                if(res.success){
                    _this.rechargeInfo = res.data;
                    _this.visible = true;
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        handleOk(){
            let _this = this;
            if(_this.rechargeInfo == ''){
                _this.$message.warning('请输入充值信息');
                return;
            }
            const params = {
                'accountId': _this.account.id,
                'rechargeInfo': _this.rechargeInfo,
            }
            updateAccountRechargeInfo(params)
            .then(res => {
                if(res.success){
                    _this.$notification['success']({
                        message: '温馨提示',
                        description: '设置成功',
                        duration: 8
                    })
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 设置提现账户
        setWidthdraw(){
            let _this = this
            getLaborWithdrawConfig(_this.withdrawAccount.accountId)
            .then(res=>{
                if(res.success){
                    _this.withdrawAccount = JSON.parse(JSON.stringify(res.data));
                    _this.withdrawAccount.accountId = _this.withdrawAccount.accountId ?? _this.accountId;
                    _this.withdrawConfigVisible = true;
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        withdrawConfigHandleOk(){
            let _this = this
            _this.$refs.ruleForm.validate(valid => {
                if(valid){
                    updateWithdrawAccountConfig(_this.withdrawAccount)
                    .then(res=>{
                        if(res.success){
                            _this.$notification['success']({
                                message: '温馨提示',
                                description: '设置成功',
                                duration: 8
                            })
                            _this.withdrawConfigVisible = false;
                        }else{
                            _this.$notification['error']({
                                message: '温馨提示',
                                description: res.errMessage,
                                duration: 8
                            })
                        }
                    })
                }
            })
        },
        // 设置交易密码
        setPayPassword(){
            this.payPasswordVisible = true;
        },
        // 确认交易密码校验
        handlePasswordCheck (rule, value, callback) {
            if (value === undefined) {
                callback(new Error('请再次输入交易密码'))
            }
            if (value && this.payPassword.dealPassword !== this.payPassword.confirmPassword) {
                callback(new Error('两次密码输入不一致'))
            }
            callback()
        },
        // 获取验证码
        getCaptcha (e) {
            e.preventDefault()
            let _this = this
            _this.smsSendBtn = true
            const interval = window.setInterval(() => {
                if (_this.time-- <= 0) {
                    _this.time = 60
                    _this.smsSendBtn = false
                    window.clearInterval(interval)
                }
            }, 1000)
            const hide = _this.$message.loading('验证码发送中..', 0)
            getSmsCaptcha({ 'phone': _this.userPhone , 'businessType': 'CHANGE_DEAL_PASSWORD' }).then(res => {
                setTimeout(hide, 2500)
                if(res.success){
                    _this.$notification['success']({
                        message: '提示',
                        description: `验证码已发送至尾号${_this.userPhone.substring(7)}上，请注意查收`,
                        duration: 8
                    })
                }else{
                    setTimeout(hide, 1)
                    clearInterval(interval)
                    _this.time = 60
                    _this.smsSendBtn = false
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            }).catch(err => {
                setTimeout(hide, 1)
                clearInterval(interval)
                _this.time = 60
                _this.smsSendBtn = false
                
            })
        },
        payPasswordHandleOk(){
            let _this = this
            _this.$refs.payPasswordRuleForm.validate(valid => {
                if(valid){
                    setPayPassword(_this.payPassword)
                    .then(res=>{
                        if(res.success){
                            _this.$notification['success']({
                                message: '温馨提示',
                                description: '设置成功',
                                duration: 8
                            })
                            _this.payPasswordVisible = false;
                        }else{
                            _this.$notification['error']({
                                message: '温馨提示',
                                description: res.errMessage,
                                duration: 8
                            })
                        }
                    })
                }
            })
        },
        // 获取是否设置过交易密码
        getHasPaypassword(){
            let _this = this
            getHasPayPassword(_this.payPassword.accountId)
            .then(res=>{
                if(res.success){
                    _this.hasPayPassword = res.data;
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 修改交易密码
        updatePayPasswordBtn(){
            this.updatePayPasswordVisible = true;
        },
        forgetPassword(){
            this.updatePayPasswordVisible = false;
            this.payPasswordVisible = true;
        },
        updatePayPasswordHandleOk(){
            let _this = this
            console.log('111')
            _this.$refs.updatePayPasswordRuleForm.validate(valid => {
                if(valid){
                    updatePayPassword(_this.updatePayPasswords)
                    .then(res=>{
                        if(res.success){
                            _this.$notification['success']({
                                message: '温馨提示',
                                description: '修改成功',
                                duration: 8
                            })
                            _this.updatePayPasswordVisible = false;
                        }else{
                            _this.$notification['error']({
                                message: '温馨提示',
                                description: res.errMessage,
                                duration: 8
                            })
                        }
                    })
                }
            })
        },
        // 切换是否需要支付密码
        needDealPasswordOnChange(){
            console.log('111')
            let _this = this;
            _this.isCheck = true;
            const params = {
                'accountId': _this.accountId,
                'needDealPassword': _this.account.needDealPassword == '0' ? '1' : '0',
            }
            changeAccountDealPasswordStatus(params)
            .then(res => {
                _this.isCheck = false;
                if(res.success){
                    _this.$notification['success']({
                        message: '温馨提示',
                        description: '修改成功',
                        duration: 8
                    })
                    _this.getDetail(_this.accountId);
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
    }
}

</script>
<style scoped>
.detail /deep/ .ant-page-header-heading-title{
    float: none;
}
</style>